package com.similarity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.model.DataModel;
import com.model.TagBasedUserDataModel;

public class TagBasedUserSimilarity{

	private TagBasedUserDataModel datamodel;
	
	public TagBasedUserSimilarity(DataModel datamodel)
	{
		this.datamodel=(TagBasedUserDataModel)datamodel;
	
	}
	
	public Double calculateUserSimilarity(long requestInitiator,long ConsideredUser) {
		Double userSimilarity = 0.0d;
		System.out.println("Current user :"+requestInitiator);
		Map<Long, ArrayList<String>> requestInitiatorTagVector = datamodel.getTagVector(requestInitiator);
		Map<Long, ArrayList<String>> consideredUserTagVector = datamodel.getTagVector(ConsideredUser);
		
		Iterator<Long> iter = consideredUserTagVector.keySet().iterator(); 
		Integer commonlyTaggedimages = 0;
		Double sum = 0.0d;
		
		while (iter.hasNext()) {
			Long imageID  = (Long)iter.next();
			if (requestInitiatorTagVector.containsKey(imageID)) {
				commonlyTaggedimages++;
				sum += calculateTagVectorSimilarity(consideredUserTagVector.get(imageID), requestInitiatorTagVector.get(imageID)) + 1;
				
			}
				
		}
		
		userSimilarity = sum/(2*commonlyTaggedimages);
		
		if(sum==0||commonlyTaggedimages==0){
			userSimilarity=0.0;
		}
		
		return userSimilarity + 1;
		
	}
	
	public Double calculateTagVectorSimilarity(ArrayList<String> consideredUserTagVector,ArrayList<String> requestInitiatorTagVector ) {
		 Double tagVectorSimilarity = 0.0d;
		 Integer intersection = 0;
		 Iterator<String> iter = consideredUserTagVector.iterator();	
		 while (iter.hasNext()) {
				String tag  = iter.next();
				if(requestInitiatorTagVector.contains(tag)){
					intersection++;
					requestInitiatorTagVector.remove(tag);
				}
				
		 }
		 tagVectorSimilarity = (Double)(intersection/calculateunion(consideredUserTagVector, requestInitiatorTagVector));
		 return tagVectorSimilarity;
		}
	 
	public Double calculateunion(ArrayList<String> consideredUserTagVector,ArrayList<String> requestInitiatorTagVector ) {
		 ArrayList<String> uniqueTags = new ArrayList<String>();
		 Iterator<String> iter = consideredUserTagVector.iterator();	
		 while (iter.hasNext()) {
				String tag  = iter.next();
				if (!uniqueTags.contains(tag)) {
					uniqueTags.add(tag);
					
				}
				
		 }
		 
		 iter = requestInitiatorTagVector.iterator();			 
		 while (iter.hasNext()) {
				String tag  = iter.next();
				if (!uniqueTags.contains(tag)) {
					uniqueTags.add(tag);
					
				}
				
		 }
		 return Double.parseDouble(((Integer)uniqueTags.size()).toString());
		
	}

}
